import React from 'react';
import {
  Animated,
  StyleProp,
  View,
  ViewStyle,
  TouchableOpacity as RNTouchableOpacity,
  GestureResponderEvent,
} from 'react-native';
import { TContainerProps } from './Types';
import { bs, isAnimated } from './convert';
import { SafeAreaView } from 'react-native-safe-area-context';
import { TouchableOpacity } from 'react-native-gesture-handler';

export function ContainerHoc(pprops?: TContainerProps) {
  return function Container(props: TContainerProps): JSX.Element {
    let Component:
      | React.ComponentClass<any>
      | React.ForwardRefExoticComponent<any>
      | Animated.AnimatedComponent<typeof View> = View;
    props = Object.assign({}, pprops, props);
    if (props.sf) Component = SafeAreaView;
    if (props.onPress || props.onLongPress) {
      if (props.hs === undefined) {
        props.hs = 10;
      }
      props.hitSlop = {
        top: +props.hs,
        bottom: +props.hs,
        left: +props.hs,
        right: +props.hs,
      };
      delete props.hs;
      if (props.nf) props.activeOpacity = 1;
      Component = props.ges ? TouchableOpacity : RNTouchableOpacity;
      const onPress = props.onPress;
      props.onPress = (e: GestureResponderEvent) => {
        onPress?.(e);
      };
      props.pressRetentionOffset = pressRetentionOffset;
    }
    const animated =
      isAnimated(props.op) ||
      isAnimated(props.tx) ||
      isAnimated(props.ty) ||
      isAnimated(props.rt) ||
      isAnimated(props.scale) ||
      isAnimated(props.sx) ||
      isAnimated(props.sy);
    Component = React.useMemo(() => {
      if (!animated) return Component;
      return Animated.createAnimatedComponent(Component);
    }, [Component, animated]);
    const style: StyleProp<ViewStyle> = bs(props);
    return (
      <Component {...props} style={[style, props.style]} ref={props.innerRef} />
    );
  };
}

const pressRetentionOffset = {
  top: 2,
  left: 2,
  bottom: 2,
  right: 2,
};
